<template>
  <div class="app-container">
    <el-form :inline="true" :model="recordInfo.queryForm" class="demo-form-inline">

      <el-form-item label="活动名称/编号">
        <el-input v-model="recordInfo.queryForm.activityName" placeholder="活动名称/编号" clearable style="width: 220px;" />
      </el-form-item>

      <el-form-item label="充值优惠">
        <el-select v-model="recordInfo.queryForm.rewardType" clearable placeholder="充值优惠" style="width: 220px">
          <el-option v-for="item in rechargeOfferList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="活动状态">
        <el-select v-model="recordInfo.queryForm.activityState" clearable placeholder="活动状态" style="width: 220px">
          <el-option v-for="item in activityStatusList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <OrganizationSelector
        v-model="organizationQuery"
        :user-type="userInfo.organizationType"
      />

      <!-- <el-form-item label="运营状态">
        <el-select v-model="recordInfo.queryForm.operationState" clearable placeholder="运营状态" style="width: 220px">
          <el-option v-for="item in operationStatusList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="创建日期">
        <el-date-picker
          v-model="createTimeValue"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="defaultTime"
          @change="dateChange('createTimeValue')"
          style="width: 300px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
        <!-- <el-button @click="viewOrderDetail({orderId:1})">打开详情</el-button>
        <el-button @click="goDetail()">充值订单详情</el-button> -->
      </el-form-item>
    </el-form>

    <div style="display: flex;justify-content: space-between;align-items: center; margin-bottom: 10px;">
      <h5 style="margin: 0; font-size: 16px;">活动列表</h5>
    </div>

    <el-table
      v-loading="recordInfo.loading"
      class="table-default"
      :data="recordInfo.list"
      border
      style="width: 100%"
      max-height="600"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column label="活动信息" width="250" align="center">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.activityName" placement="top-start">
            <span class="text-ellipsis">{{ scope.row.activityName }}</span>
          </el-tooltip>
          <el-button type="text" size="small" @click="goDetail(scope.row)">{{ scope.row.rechargeActivityId }}</el-button>
        </template>
      </el-table-column>

      <!-- <el-table-column prop="totalRechargeAmount" label="充值金额" align="center" /> -->
      <el-table-column prop="rewardType" label="充值优惠" align="center"  />
      <el-table-column prop="totalRechargeOrderCount" label="充值订单" align="center" />

      <el-table-column prop="activityState" label="活动状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.activityState)">{{ scope.row.activityStateText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期" align="center" />
      <el-table-column prop="headquartersName" label="所属总部" width="200"  align="center"/>
      <el-table-column prop="chainName" label="所属机构" width="200"  align="center"/>
      <el-table-column prop="organizationName" label="所属门店" width="200"  align="center"/>

    </el-table>

    <pagination
      v-show="recordInfo.total > 0"
      :total="recordInfo.total"
      :page.sync="recordInfo.queryForm.page"
      :limit.sync="recordInfo.queryForm.pageSize"
      @pagination="getRecordList"
      :page-sizes="[10, 20, 50, 100]"
    />

    <activity-detail-dialog
      :visible.sync="showDetailDialog"
      :order-id="currentOrderId"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import filters from '@/filters/index'
import ListMixin from '@/mixins/modules/list'
import messageMixin from '@/mixins/modules/message'
import Pagination from '@/components/Pagination'
import ActivityDetailDialog from './components/ActivityDetailDialog.vue'
import OrganizationSelector from '@/views/member/components/OrganizationSelector.vue'

export default {
  components: {
    ActivityDetailDialog,
    Pagination,
    OrganizationSelector

  },
  filters: { ...filters },
  mixins: [ListMixin, messageMixin],
  data() {
    return {
      showDetailDialog: false,
      currentOrderId: null,
      createTimeValue: null,

      recordInfo: {
        queryForm: {
          page: 1,
          pageSize: 10,
          getOrganizationNameState:1,
          orderBy: 'createTimeDesc',
          // 查询表单字段
          activityName: '',
          rewardType: '',
          activityState: '',
          operationState: '',
        headquartersId: '', // 清空
    chainId: '',        // 清空
    organizationId: '',        // 清空
        },
        requestUrl: this.$api.getRechargeActivityList, // 假设存在活动列表接口
        list: [],
        total: 0,
        loading: false
      },

      // 静态数据列表（模拟）
      rechargeOfferList: [{ name: '赠送金额', value: 1 }, { name: '赠送礼品', value: 2 }],
      activityStatusList: [
        { name: '未开始', value: 1, tag: 'info' },
        { name: '进行中', value: 2, tag: 'success' },
        { name: '已结束', value: 3, tag: 'danger' },
        { name: '已关闭', value: 4, tag: 'Warning' }
      ],
      operationStatusList: [
        { name: '开启', value: 1, tag: 'success' },
        { name: '已关闭', value: 2, tag: 'danger' }
      ],

      changeDateNameInfo: {
        createTimeValue: ['startTime', 'endTime']
      },

      // 覆盖 Mixin 的 getListCallback，用于处理列表数据的格式化
      getListCallback: (res) => {
        if (res.list && res.list.length > 0) {
          res.list.forEach(item => {
            // 1. 格式化时间
            item.createTime = this.$commonUtils.getShowTime(item.createTime)

            // 2. 格式化金额和数量
            item.totalRechargeAmount = '¥' + parseFloat(item.totalRechargeAmount).toFixed(2)
            item.totalRechargeOrderCount = item.totalRechargeOrderCount + '单'

            // 3. 状态映射
            const actStatus = this.activityStatusList.find(s => s.value === item.activityState)
            item.activityStateText = actStatus ? actStatus.name : '未知'

            const opStatus = this.operationStatusList.find(s => s.value === item.operationState)
            item.operationStateText = opStatus ? opStatus.name : '未知'

            const rewardTypeStatus = this.rechargeOfferList.find(s => s.value === item.rewardType)
            item.rewardType = rewardTypeStatus ? rewardTypeStatus.name : '未知'
            item.totalGiftAmount = '¥' + parseFloat(item.totalGiftAmount).toFixed(2)
          })
        }
        // 更新列表和总数
        this.recordInfo.list = res.list || []
      },

      // 覆盖 Mixin 的 beforeRequest
      beforeRequest: () => {
        // 创建日期范围处理
        this.changeDate(this.createTimeValue, 'createTimeValue')

        // 确保 returnCount 逻辑正确
        this.recordInfo.queryForm.returnCount = this.recordInfo.queryForm.page === 1
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    organizationQuery: {
      get() {
        return {
          headquartersId: this.recordInfo.queryForm.headquartersId,
          chainId: this.recordInfo.queryForm.chainId,
          storeId: this.recordInfo.queryForm.organizationId,
        };
      },
      set(newVal) {
        this.recordInfo.queryForm.headquartersId = newVal.headquartersId;
        this.recordInfo.queryForm.chainId = newVal.chainId;
        this.recordInfo.queryForm.organizationId = newVal.storeId;
      }
    }
  },

  methods: {
    viewOrderDetail(item) {
      this.currentOrderId = item.orderId // 传入订单ID
      this.showDetailDialog = true       // 显示弹窗
    },
    // 根据活动状态获取 El-Tag 的主题
    getStatusTagType(status) {
      const statusMap = {
        1: 'info', // 未开始
        2: 'success', // 进行中
        3: 'danger', // 已结束
        4: 'Warning', // 已关闭
      }
      return statusMap[status] || 'info'
    },

    // 根据运营状态获取 El-Tag 的主题
    getOperationTagType(status) {
      const statusMap = {
        1: 'success', // 开启中
        2: 'danger',  // 已关闭
      }
      return statusMap[status] || 'info'
    },

    // 查询按钮，利用 Mixin 的 getRecordList
    search() {
      this.recordInfo.queryForm.page = 1
      this.getRecordList()
    },

    // 重置表单，清空所有查询条件
    resetForm() {
      // 业务字段清空
      this.recordInfo.queryForm = {
        page: 1,
        pageSize: 10,
        orderBy: 'createTimeDesc',
        getOrganizationNameState:1,
        activityName: '',
        rewardType: '',
        organizationId: '',
        activityState: '',
        operationState: '',
        headquartersId: '', // 清空
    chainId: '',        // 清空
      }
      // 日期清空
      this.createTimeValue = null
      // 重新查询
      this.search()
    },

    // 查看活动详情 (跳转新 Tab)
    // goDetail1(item) {
    //   this.$addTab('activityDetail', {
    //     activityId: item
    //   }, '活动详情 - ' + item.activityName)
    // },


    // 查看订单详情 (跳转新 Tab)
    goDetail(item) {
      this.$addTab('memberrechargeActivityDetail', {
        item
      }, '订单详情 - ' + item.activityName)
    },

    // 编辑活动
    editActivity(item) {
      this.$addTab('activityForm', {
        activityId: item
      }, '编辑活动 - ' + item.activityName)
    },

    // 新增活动
    addActivity() {
      this.$addTab('activityForm', {}, '新增活动')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
.demo-form-inline {
  padding-bottom: 5px;
  .el-form-item {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

// 表格内容省略号
.text-ellipsis {
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

// 使金额列右对齐
::v-deep .el-table {
    // 充值金额 (第3列)
    .el-table__cell:nth-child(3) {
        .cell {
            text-align: right;
        }
    }
}
</style>
